<template>
  <view>
    <swiper :indicator-dots="true" :autoplay="true" style="height:400rpx">
      <swiper-item v-for="(img, idx) in swiperList" :key="idx">
        <image :src="img" style="width:100%;height:100%;" mode="aspectFit" />
      </swiper-item>
    </swiper>
    <view class="detail-container">
      <view class="title">{{ goodsInfo.title }}</view>
      <view class="price-box">
        <text class="sell-price">¥{{ goodsInfo.sell_price }}</text>
        <text class="market-price">¥{{ goodsInfo.market_price }}</text>
      </view>
      <view class="desc">{{ goodsInfo.zhaiyao }}</view>
      <view class="content" v-html="goodsInfo.content"></view>
    </view>
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <button class="cart-btn" @click="showPopup = true; popupType = 'cart'">加入购物车</button>
      <button class="buy-btn" @click="showPopup = true; popupType = 'buy'">立即购买</button>
    </view>
    <!-- 商品配置弹框 -->
    <view v-if="showPopup" class="popup-mask" @click.self="showPopup = false">
      <view class="popup-panel" @click.stop>
        <!-- 商品信息展示 -->
        <view class="popup-goods-info">
          <image :src="swiperList[0]" class="popup-goods-img" mode="aspectFit"></image>
          <view class="popup-goods-detail">
            <view class="popup-goods-title">{{ goodsInfo.title }}</view>
            <view class="popup-goods-price">
              <text class="popup-sell-price">¥{{ goodsInfo.sell_price }}</text>
              <text class="popup-market-price">¥{{ goodsInfo.market_price }}</text>
            </view>
          </view>
        </view>
        <view class="popup-title">选择商品数量</view>
        <view class="popup-content">
          <view class="popup-row">
            <text>数量：</text>
            <button class="num-btn" @click="changeCount(-1)" :disabled="count<=1">-</button>
            <text class="count">{{ count }}</text>
            <button class="num-btn" @click="changeCount(1)">+</button>
          </view>
        </view>
        <!-- 弹窗按钮 -->
        <button
          class="popup-add-btn"
          v-if="popupType === 'cart'"
          @click="handleAddToCart"
        >
          添加购物车
        </button>
        <button
          class="popup-add-btn"
          v-else
          @click="handleBuyNow"
        >
          立即支付
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { request, BASE_URL } from '@/Requset/request'

const goodsInfo = ref<any>({})
const thumbImages = ref<any[]>([])
const swiperList = ref<string[]>([])
const current = ref<number>(0)
const history = ref<any[]>([])

const showPopup = ref(false)
const popupType = ref<'cart' | 'buy'>('cart')
const count = ref(1)

onLoad((options) => {
  const id = options.id
  // 获取商品详情
  request({
    url: BASE_URL + `api/getgoodsinfo/${id}`,
  }).then((res: any) => {
    console.log('商品详情接口返回:', res)
    if (res.data && res.data.status === 1) {
      goodsInfo.value = res.data.message
      // 在设置 goodsInfo.content 前处理图片标签
      goodsInfo.value.content = goodsInfo.value.content
        // 移除 img 上原有的 width/height/style 属性
        .replace(/<img[^>]*?>/g, (imgTag) => {
          let newTag = imgTag
            .replace(/\swidth="[^"]*"/gi, '')
            .replace(/\sheight="[^"]*"/gi, '')
            .replace(/\sstyle="[^"]*"/gi, '');
          return newTag.replace(
            /<img/gi,
            '<img style="max-width:100%;height:auto;display:block;margin:0 auto;"'
          );
        })
        // 移除 table/td/div 上的 width 和 style 属性
        .replace(/<(table|td|div)[^>]*?>/gi, (tag) => {
          return tag
            .replace(/\swidth="[^"]*"/gi, '')
            .replace(/\sstyle="[^"]*"/gi, '');
        });
      console.log('商品详情数据:', goodsInfo.value)
    }
  })
  // 获取商品图片
  request({
    url: BASE_URL + `api/getthumbimages/${id}`,
  }).then((res: any) => {
    console.log('商品图片接口返回:', res)
    if (res.data && res.data.status === 0) {
      thumbImages.value = res.data.message
      swiperList.value = res.data.message.map((img: any) => img.src)
      console.log('轮播图图片数组:', swiperList.value)
    }
  })
})

// 页面显示时读取历史记录
onShow(() => {
  history.value = uni.getStorageSync('history') || []
  console.log('读取历史', history.value)
})

//轮播
function handleClick(e) {
  console.log(e)
}
function onChange(e) {
  console.log(e)
}

function saveHistory(item) {
  let historyData = uni.getStorageSync('history') || []
  historyData = historyData.filter(i => i.id !== item.id)
  historyData.unshift(item)
  if (historyData.length > 20) historyData = historyData.slice(0, 20)
  uni.setStorageSync('history', historyData)
}

function handleProductClick(item) {
  saveHistory(item)
  uni.navigateTo({
    url: `/pages/detail/detail?id=${item.id}`
  })
}

// 数量加减
function changeCount(val: number) {
  if (count.value + val < 1) return
  count.value += val
}

// 登录状态判断
function isLogin() {
  // 假设 token 存在即为已登录
  return !!uni.getStorageSync('token')
}

function handleAddToCart() {
  if (!isLogin()) {
    uni.navigateTo({
      url: `/pages/Login/Login?redirect=detail&id=${goodsInfo.value.id}`
    })
    return
  }
  let cartList = uni.getStorageSync('cartList') || []
  const idx = cartList.findIndex(i => i.id === goodsInfo.value.id)
  if (idx > -1) {
    cartList[idx].count += count.value
  } else {
    cartList.push({ id: goodsInfo.value.id, count: count.value })
  }
  uni.setStorageSync('cartList', cartList)
  showPopup.value = false
  count.value = 1
  uni.showToast({ title: '已加入购物车', icon: 'success' })
}

function handleBuyNow() {
  if (!isLogin()) {
    uni.navigateTo({
      url: `/pages/Login/Login?redirect=${encodeURIComponent('/pages/detail/detail?id=' + goodsInfo.value.id)}`
    })
    return
  }
  // 生成订单号（年月日+时间戳+随机数）
  const now = new Date()
  const orderId = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2,'0')}${now.getDate().toString().padStart(2,'0')}${Date.now().toString().slice(-6)}${Math.floor(Math.random()*1000).toString().padStart(3,'0')}`

  // 存储订单商品（带图片）
  uni.setStorageSync('orderGoods', [{
    ...goodsInfo.value,
    count: count.value,
    // 保证图片字段有值
    thumb_path: swiperList.value[0] || goodsInfo.value.thumb_path || goodsInfo.value.image || ''
  }])
  // 存储订单号
  uni.setStorageSync('orderId', orderId)
  // 存储订单总价
  uni.setStorageSync('orderTotalPrice', goodsInfo.value.sell_price * count.value)
  uni.navigateTo({
    url: '/pages/Order_page/Order_page'
  })
  showPopup.value = false
  count.value = 1
}
</script>

<style>
.detail-container {
  padding: 24rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}
.price-box {
  margin-bottom: 12rpx;
}
.sell-price {
  color: #e64340;
  font-size: 32rpx;
  margin-right: 16rpx;
}
.market-price {
  color: #999;
  text-decoration: line-through;
  font-size: 24rpx;
}
.desc {
  color: #666;
  margin-bottom: 20rpx;
}
.content {
  padding: 0 !important;
}
.content {
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  padding: 0 8rpx;
}
.content img {
  max-width: 100% !important;
  height: auto !important;
  display: block !important;
  margin: 0 auto !important;
}
.content p,
.content div {
  margin: 0 !important;
  padding: 0 !important;
}
.content table,
.content td,
.content tr {
  width: 100% !important;
  max-width: 100% !important;
  box-sizing: border-box;
  overflow-x: auto;
}
.thumb-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}
.thumb-img {
  width: 100%;
  border-radius: 8rpx;
}

/* 弹框样式 */
.popup-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.popup-panel {
  width: 100%;
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  padding: 32rpx 24rpx 24rpx 24rpx;
  box-sizing: border-box;
  animation: popupUp 0.2s;
}
@keyframes popupUp {
  from { transform: translateY(100%);}
  to { transform: translateY(0);}
}
.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 24rpx;
}
.popup-content {
  margin-bottom: 32rpx;
}
.popup-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.num-btn {
  width: 48rpx;
  height: 48rpx;
  border: none;
  background: #f5f5f5;
  font-size: 32rpx;
  border-radius: 50%;
  text-align: center;
  line-height: 48rpx;
}
.count {
  font-size: 28rpx;
  width: 48rpx;
  text-align: center;
}
.popup-add-btn {
  width: 100%;
  height: 80rpx;
  background: #e64340;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
  margin-top: 16rpx;
}

/* 弹框商品信息样式 */
.popup-goods-info {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}
.popup-goods-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  background: #f5f5f5;
  object-fit: contain; /* 保证图片完整显示 */
}
.popup-goods-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}
.popup-goods-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #222;
}
.popup-goods-price {
  display: flex;
  align-items: baseline;
  gap: 16rpx;
}
.popup-sell-price {
  color: #e64340;
  font-size: 30rpx;
  font-weight: bold;
}
.popup-market-price {
  color: #999;
  text-decoration: line-through;
  font-size: 22rpx;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  background: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0,0,0,0.05);
  padding: 16rpx 24rpx;
  gap: 24rpx;
}
.cart-btn, .buy-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
}
.cart-btn {
  background: #ffe1e1;
  color: #e64340;
}
.buy-btn {
  background: #e64340;
  color: #fff;
}
</style>

